import { Injectable, Inject } from "@nestjs/common";
import { RedisClientType } from "redis";

@Injectable()
export class VedioService {
  private userMap: Map<any, any>;

  constructor(@Inject("REDIS_CLIENT") private redisClient: RedisClientType) {
    this.userMap = new Map(); // user - > socket
    this.redisClient = redisClient;
    this.redisClient.on("connect", function () {
      console.log("redis 连接成功");
    });
    this.redisClient.on("error", function (err) {
      console.log("redis 连接异常 ", err);
    });
    this.redisClient.on("reconnecting", (stats) => {
      console.log("redis重连", stats);
    });
  }

  userListSet(userId: any, s: any) {
    this.userMap.set(userId, s);
  }

  userListDelete(userId: any) {
    this.userMap.delete(userId);
  }

  async hSet(key, hashkey, hashval) {
    if (typeof hashval === "object") {
      hashval = JSON.stringify(hashval);
    }
    await this.redisClient.hmset(key, hashkey, hashval);
  }

  async hGetAll(key) {
    const promise = new Promise((resolve, reject) => {
      this.redisClient.hgetall(key, function (err, val) {
        if (err) {
          reject(err);
          return;
        }
        if (val == null) {
          resolve(null);
          return;
        }
        resolve(val);
      });
    });
    return promise;
  }

  async hDel(key, hashkey) {
    await this.redisClient.hdel(key, hashkey);
  }

  async getHello() {
    // console.log(this.redisClient);
    return "helloRedis";
  }
}
